package com.example.demo.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author LF
 * @date 2021/4/21 - 13:39
 */
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

    /**
     * 业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = {BizException.class})
    @ResponseBody
    public ResultBody exceptionHandler(BizException e){
        log.info("业务异常--->{}", e.getMessage());
        return ResultBody.error(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 空指针异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultBody nullPointerException(NullPointerException e){
        log.info("空指针异常--->{}", e.getMessage());
        return ResultBody.error(CommonEnum.BODY_NOT_MATCH);
    }

    /**
     * 算术运算异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = ArithmeticException.class)
    @ResponseBody
    public ResultBody arithmeticException(ArithmeticException e){
        log.info("算术运算异常--->{}", e.getMessage());
        return ResultBody.error(e.getMessage());
    }

    /**
     * 未知异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultBody otherError(Exception e){
        log.info("未知异常--->{}", e.getMessage());
        return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }
}
